package com.jxjiang.chatapplication;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.jxjiang.chatapplication.client.ChatClientAndroid;

import java.lang.ref.WeakReference;

import top.xx252016.coreClient.base.Contract;


public class MainActivity extends AppCompatActivity {
    Handler mTheadHandler;
    Contract.AppContract mContract;
    Contract.SubThreadContract mSubThreadContract;

    ChatService mChatService;
    TextView textView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView = findViewById(R.id.tv_msg);
        mContract = new InnerAppContract(new WeakReference<TextView>(textView));
    /*    new Thread(new Runnable() {
            @Override
            public void run() {
                mSubThreadContract = new ChatClientAndroid(mContract);
                mSubThreadContract.start();

            }
        }).start();*/
        final EditText editText = findViewById(R.id.send_msg);
        Button button = findViewById(R.id.button);
        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit(editText.getText().toString());
            }
        });

        Intent intent = new Intent(this, ChatService.class);
        startService(intent);
        bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE);
    }
    private void submit(final String string){
//        mSubThreadContract.fecth2Socket(string);
        mChatService.submit2Handler(string);
    }

    ServiceConnection mServiceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mChatService = ((ChatService.LocalBinder)service).getService();
            mChatService.setContract(mContract);
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        unbindService(mServiceConnection);
       // stopService(new Intent(this, ChatService.class));
    }

    public static class InnerAppContract implements Contract.AppContract {

        WeakReference<TextView> mTextView;
        public InnerAppContract(WeakReference<TextView> textViewWeakReference){
            mTextView = textViewWeakReference;
        }
        @Override
        public void readFromSocket(String str) {
            if(mTextView.get()!=null)
                mTextView.get().setText(str);
        }
    }

}
